﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Configuration;
using System.Data;

namespace DAL
{
    public class SqlHelper
    {
        static string connectionString = ConfigurationManager.ConnectionStrings["SqlLite"].ConnectionString;
        static DbProviderFactory fact = DbProviderFactories.GetFactory("System.Data.SQLite");

        static SqlHelper()
        {
            //connectionString = "Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "\\DataBase\\ServiceCenter.db";
            connectionString = connectionString.Replace("{AppDir}", AppDomain.CurrentDomain.BaseDirectory);
        }
        public static DbConnection GetConnection()
        {
            DbConnection connection = fact.CreateConnection();
            connection.ConnectionString = connectionString;
            connection.Open();
            connection.BeginTransaction();
            return connection;
        }

        public static DbCommand GetCommand(string commandText,DbTransaction trans=null)
        {
            DbCommand command = fact.CreateCommand();
            if (trans == null)
            {
                command.Connection = GetConnection();
            }
            else
            {
                command.Connection = trans.Connection;
                command.Transaction = trans;
            }
            
            command.CommandText = commandText;
            return command;
        }

        public static DbCommand GetCommand()
        {
            return GetCommand("");
        }

        public static void Close(DbConnection connection, DbDataReader reader = null)
        {
            if (connection != null && connection.State != ConnectionState.Closed)
            {
                connection.Close();
            }
        }

        public static void Close(DbCommand command, DbDataReader reader = null)
        {
            Close(command.Connection, reader);
        }

        public static DbParameter CreateParameter(string name, object value)
        {
            DbParameter parameter = fact.CreateParameter();
            parameter.ParameterName = name;
            parameter.Value = value;
            return parameter;
        }
    }
}
